package net.v.autopatcher;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.zip.GZIPInputStream;

import autoupdate.test.AutoUpdater;


public class Patch{
	

	public static void main(String[] args){
		
		patchAll();
		
		System.out.println("Ending patching.");
	}
	
	public static void patchAll(){
		System.out.println("patching...");
		File dir = new File(".");
		
//		 This filter only returns directories
	    FilenameFilter fileFilter = new FilenameFilter() {
	        public boolean accept(File dir, String name) {
	            return name.indexOf(AutoUpdater.UPDATE_FILE_SUFFIX) > -1;
	        }
	    };

	    
	    String[] children = dir.list(fileFilter);
	    if (children == null) {
	        // Either dir does not exist or is not a directory
	    } else {
	        for (int i=0; i<children.length; i++) {
	            // Get filename of file or directory
	            String filename = children[i];
	            System.out.println(filename);
	            patch(filename);
	        }
	    }
	}
	
	public static void patch(String filename){
//		start timing
		long startMillis = System.currentTimeMillis();
		String filenameOut = filename.replace(AutoUpdater.UPDATE_FILE_SUFFIX, AutoUpdater.UPDATE_REPLACEMENT_SUFFIX);

		try{
			File fileIn = new File(filename);
			File fileOut = new File(filenameOut);
			GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(new FileInputStream(fileIn)));
			DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileOut)));
	
			int bytesRead = 0;
			int totalBytes = 0;
			byte data[] = new byte[1024];
			while((bytesRead = gis.read(data)) > -1){
				totalBytes += bytesRead;
				
				dos.write(data,0,bytesRead);
				
			}

			dos.flush();
			dos.close();
			gis.close();
			
			fileIn.delete();
			
	//		End timing
			System.out.println((System.currentTimeMillis() - startMillis) + "ms");
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

}
